package controller

import (
	"gin_vote/cache"
	"gin_vote/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type PlayerController struct {
}

func (p PlayerController) GetPlayers(c *gin.Context) {
	aidStr := c.DefaultPostForm("aid", "0")
	aid, _ := strconv.Atoi(aidStr)

	players, err := models.GetPlayers(aid, "id asc")
	if err != nil {
		ReturnError(c, 4001, "没有相关信息")
		return
	}
	ReturnSuccess(c, 0, "success", players, int64(len(players)))
}

func (p PlayerController) GetRanking(c *gin.Context) {
	aidStr := c.DefaultPostForm("aid", "0")
	aid, _ := strconv.Atoi(aidStr)

	var redisKey string
	redisKey = "ranking:" + aidStr
	rs, err := cache.Rdb.ZRevRange(cache.Rctx, redisKey, 0, -1).Result()
	if err == nil && len(rs) > 0 {
		var players []models.Player
		for _, value := range rs {
			id, _ := strconv.Atoi(value)
			player, _ := models.GetPlayerByPlayerId(id)
			if player.Id > 0 {
				players = append(players, player)
			}
		}
		ReturnSuccess(c, 0, "success", players, int64(len(players)))
		return
	}
	rsDb, errDb := models.GetPlayers(aid, "score desc")
	if errDb != nil {
		ReturnError(c, 4001, "没有相关信息")
		return
	}

	for _, value := range rsDb {
		cache.Rdb.ZAdd(cache.Rctx, redisKey, cache.ZScore(value.Id, value.Score)).Err()
	}
	cache.Rdb.Expire(cache.Rctx, redisKey, 24*time.Hour)
	ReturnSuccess(c, 0, "success", rs, 1)
}
